use windows::core::{h, w};
use windows::Win32::Foundation::{ HWND, LPARAM, LRESULT, WPARAM};
use windows::Win32::Graphics::Gdi::{UpdateWindow, ValidateRect};
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::UI::WindowsAndMessaging::{WM_CREATE, WM_PAINT, WM_SIZE, WM_COMMAND, WM_DESTROY, CreateWindowExW, DefWindowProcW, DispatchMessageW, GetMessageW, LoadCursorW, MessageBoxW, PostQuitMessage, RegisterClassW, CS_HREDRAW, CS_VREDRAW, CW_USEDEFAULT, IDC_ARROW, MB_OK, MSG, WINDOW_EX_STYLE, WNDCLASSW, WS_OVERLAPPEDWINDOW, WS_VISIBLE};
extern "system" fn wnd_proc(window: HWND, message: u32, w_param: WPARAM, l_param: LPARAM) -> LRESULT {
    unsafe {
        match message {
            WM_CREATE=>
                {
                    println!("创建成功");
                    LRESULT(0)
                }
            WM_PAINT => {
                println!("WM_PAINT");
                _ = ValidateRect(window, None);
                LRESULT(0)
            }
            WM_SIZE => {
                LRESULT(0)
            }
            WM_COMMAND => {
                println!("WM_COMMAND");
                match w_param.0 {
                    0 => {
                        MessageBoxW(
                            None,
                            h!("样板信息!"),
                            w!("警示"),
                            MB_OK,
                        );
                    }
                    _ => {}
                }
                LRESULT(0)
            }
            WM_DESTROY => {
                println!("WM_DESTROY");
                PostQuitMessage(0);
                LRESULT(0)
            }
            _ => DefWindowProcW(window, message, w_param, l_param),
        }
    }
}

fn main() -> windows::core::Result<()>{
    unsafe {
        let instance = GetModuleHandleW(None)?;
        let wc = WNDCLASSW {
            hCursor: LoadCursorW(None, IDC_ARROW)?,
            hInstance: instance.into(),
            lpszClassName: w!("window"),
            style: CS_HREDRAW | CS_VREDRAW,
            lpfnWndProc: Some(wnd_proc),
            ..Default::default()
        };
        RegisterClassW(&wc);
        let instance = GetModuleHandleW(None)?;
        let p= CreateWindowExW(
            WINDOW_EX_STYLE::default(),
            w!("window"),
            w!("普通窗口"),
            WS_OVERLAPPEDWINDOW | WS_VISIBLE,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            None,
            None,
            instance,
            None,
        )?;
        let _ = UpdateWindow(p);
        let mut message = MSG::default();
        while GetMessageW(&mut message, None, 0, 0).into() {
            DispatchMessageW(&message);
        }
        Ok(())
    }
}
